import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReportTable
  from 'containers/data-center/report-management/custom-report/graphic/report-table/report-table';
import CustomReportService
  from 'containers/data-center/report-management/custom-report/custom-report.service';
import 'styles/data-center/report-management/custom-report/index-table.scss';
import { deepCopy, messages } from 'share/common';
import { Popover } from 'antd';
import debounce from 'lodash.debounce';
import WaterMark from 'components/water-mark';
import noDataImg from 'images/data-center/report-no-data.png';


class IndexTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dimensionKeyMap: [],
      CopyData: {},
      ColData: [],
      metaData: [],
      headerNum: 1,
      isOutOfService: false,
      dataList: [] //透视图 返回的 数据list   因为透视图 有种  table columns 里有数据，所以这儿 多个返回
    };
    this.willReload = debounce(this.willReload, 300);
  }

  componentWillMount() {

  }

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  componentWillReceiveProps(nextProps) {
    // if (!nextProps.noRefresh) {
    //   this.willReload();
    // }
  }

  willReload = () => {
    this.onMountCharts && this.onMountCharts.ref.fetchList();
  };

  componentWillUnmount() {

  }

  //分类 维度行 维度列 & 指标
  classificationType = (list) => {
    let row = [],
      col = [],
      ind = [];
    list && list.forEach((item) => {
      if (item.belongPosition === 'row' && item.fieldType === 'dimension') {
        row.push(item);
      } else if (item.belongPosition === 'column' && item.fieldType === 'dimension') {
        col.push(item);
      } else if (item.fieldType === 'indicator') {
        ind.push(item);
      }
    });
    return { row, col, ind };
  };

  // 只填了维度行 没有维度列 结果就是 把 指标和维度行一起 当展示字段展示
  handleSituation1 = (Row, Index, isOnline) => {
    const { fullScreenMode } = this.props;
    let results = [];
    Row.forEach((item, index) => {
      results.push({
        title: (item.fieldDisplayName || item.columnDisplayName) || '-',
        key: item.columnPropName,
        fixed: 'left',
        dataIndex: item.columnPropName,
        width: (fullScreenMode ? 180 : 100),
        render: text => <span
          className={`need-limit ${fullScreenMode ? 'full-screen-mode' : ''}`}>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement="topLeft"
                       content={text}>{text}</Popover> : '-'}
          </span>
      });
    });
    Index.forEach((item, index) => {
      results.push({
        title: (item.fieldDisplayName || item.columnDisplayName) || '-',
        key: item.columnPropName,
        fixed: false,
        dataIndex: `${item.columnPropName}${isOnline ? `-${index}` : ''}`,
        width: (Index.length === index + 1) ? '' : (fullScreenMode ? 180 : 100),
        render: text => {
          if (text !== undefined && text !== null && text !== '' && item.dataType === 'bigdecimal')
            text = React.Component.prototype.filterMoney(text)
          return <span>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement={item.dataType === 'bigdecimal' ? 'topRight' : 'topLeft'}
                       content={text}>{text}</Popover> : '-'}
          </span>
        }
      });
    });
    return results;
  };

  // 先渲染 Col 到 title  然后 children 是 Index
  // 然后 Col的title 始终是第一列  他的children 是 Row
  handleSituation2 = (Row, Col, Index, isOnline) => {
    const { fullScreenMode, data } = this.props;
    const { dataList, CopyData, ColData, metaData, dimensionKeyMap } = this.state;

    let indexKeyMap = Index.map(item => item.columnPropName);

    // 根据col 来 渲染横轴

    // 取出一个指标的 条数
    let ColDataList = ColData.filter(item => item.indicatorName === indexKeyMap[0]);

    let FirstList = {};
    let DataList = [];

    FirstList = handleTitle(Col);

    if (isOnline) { // 在线 用 dataList
      DataList = ColDataList.map((singleData, dataIndex) => {
        return handleDataOnline(singleData.dimensionColumns, dataIndex);
      });
    } else { //假数据 用 data
      DataList = data.map((singleData, dataIndex) => {
        return handleData(Col, singleData, dataIndex);
      });
    }

    function handleDataOnline(data, dataIndex) {
      let copyData = deepCopy(data);
      if (Object.keys(copyData).length > 1) {
        delete copyData[Object.keys(copyData)[0]];
        return {
          title: data[Object.keys(data)[0]] || '-',
          children: [handleDataOnline(copyData, dataIndex)]
        };
      } else if (Object.keys(copyData).length === 1) {
        return {
          title: data[Object.keys(data)[0]] || '-',
          children: handleDataIndexOnline(dataIndex)
        };
      }
    }

    function handleDataIndexOnline(matchIndex) {
      return Index.map((singleIndex, indexN) => {
        return {
          width: ((ColDataList.length * Index.length) <= 10) ? '' : 150,
          title: `${singleIndex.fieldDisplayName || singleIndex.columnDisplayName}` || '-',
          dataIndex: `${singleIndex.columnPropName}-${matchIndex * indexKeyMap.length + indexN}`,
          render: (text, record, index) => {
            if (text !== undefined && text !== null && text !== '' && singleIndex.dataType === 'bigdecimal')
              text = React.Component.prototype.filterMoney(text)
            return <span>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement={singleIndex.dataType === 'bigdecimal' ? 'topRight' : 'topLeft'}
                       content={text || '-'}>{text}</Popover> : '-'}
          </span>
          }
        };
      });
    }

    function handleData(Col, data, dataIndex) {
      let copyCol = deepCopy(Col);
      if (Col.length > 1) {
        copyCol.splice(0, 1);
        return {
          title: data && data[Col[0].columnPropName] || '-',
          children: [handleData(copyCol, data, dataIndex)]
        };
      } else if (Col.length === 1) {
        return {
          title: data && data[Col[0].columnPropName] || '-',
          children: handleDataIndex(Index, dataIndex)
        };
      }
    }

    function handleDataIndex(dataIndex, matchIndex) {
      return dataIndex.map((singleIndex, indexN) => {
        return {
          // title: 'haha',
          key: Math.random() * 10000000000,
          width: 150,
          title: (singleIndex.fieldDisplayName || singleIndex.columnDisplayName) || '-',
          // key: singleIndex.columnPropName,
          dataIndex: singleIndex.columnPropName,
          render: (text, record, index) => <span>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement="topLeft"
                       content={matchIndex === index ? text : '-'}>{matchIndex === index ? text : '-'}</Popover> : '-'}
          </span>
        };
      });
    }

    function sameTitleRender(title) {
      return (
        <span className={'need-limit limit-120'}>
          {title ? <Popover zIndex={fullScreenMode ? 10030 : 1030} placement="topLeft" content={title}>{title}</Popover> : '-'}
        </span>
      );
    }

    function handleTitle(Col) {
      let copyData = deepCopy(Col);
      if (Col.length > 1) {
        copyData.splice(0, 1);
        return {
          fixed: 'left',
          title: sameTitleRender(Col[0].fieldDisplayName || Col[0].columnDisplayName),
          children: [handleTitle(copyData)]
        };
      } else if (Col.length === 1) {
        return {
          fixed: 'left',
          title: sameTitleRender(Col[0].fieldDisplayName || Col[0].columnDisplayName),
          children: handleRowTitle(Row)
        };
      }
    }

    function handleRowTitle(Row) {
      if (Row && Row.length) {
        return Row.map((item) => {
          return {
            title: sameTitleRender(item.fieldDisplayName || item.columnDisplayName),
            key: item.columnPropName,
            fixed: 'left',
            dataIndex: item.columnPropName,
            width: 120,
            render: text => {
              if (text !== undefined && text !== null && text !== '' && item.dataType === 'bigdecimal')
                text = React.Component.prototype.filterMoney(text)
              return <span className={'need-limit limit-120'}>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement={item.dataType === 'bigdecimal' ? 'topRight' : 'topLeft'}
                       content={text}>{text}</Popover> : '-'}
          </span>
            }
          };
        });
      } else {
        return [
          {
            title: '',
            key: '----',
            fixed: 'left',
            dataIndex: '----',
            width: 120,
            render: text => <span className={'need-limit limit-120'}>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement="topLeft"
                       content={'-'}>{'-'}</Popover> : '-'}
          </span>
          }
        ];
      }
    }

    return [FirstList].concat(DataList);
  };

  //selectDimensionDataList  拿来渲染  table 横向的 Name
  //selectDimensionRowDataList  拿来渲染 第一列 的数据

  handleColumns = (widget, selectShowDataList, selectDimensionRowDataList, selectDimensionDataList, selectIndicatorDataList) => {
    const { fullScreenMode } = this.props;
    if (widget.key === 'perspective') {
      if ((selectDimensionRowDataList && selectDimensionRowDataList.length) || (selectDimensionDataList && selectDimensionDataList.length)) { //编辑模式
        if (selectDimensionDataList && selectDimensionDataList.length === 0) {
          return {
            columns: this.handleSituation1(selectDimensionRowDataList, selectIndicatorDataList),
            headerNum: 1
          };
        } else {
          return {
            columns: this.handleSituation2(selectDimensionRowDataList, selectDimensionDataList, selectIndicatorDataList),
            headerNum: 1 + selectDimensionDataList.length
          };
        }
      } else { //在线模式
        let { row, col, ind } = this.classificationType(widget.reportChartDetails);
        if (col && col.length === 0) {
          return { columns: this.handleSituation1(row, ind, true), headerNum: 1 };
        } else {
          return { columns: this.handleSituation2(row, col, ind, true), headerNum: 1 + col.length };
        }
      }

    } else {
      if (selectShowDataList && selectShowDataList.length) {
        let results = [];
        let ListArray = selectShowDataList;
        ListArray && ListArray.forEach((item, index) => {
          results.push({
            title: (item.fieldDisplayName || item.columnDisplayName) || '-',
            key: item.columnPropName,
            fixed: widget.fixedColumnsNum && widget.fixedColumnsNum > index ? 'left' : false,
            dataIndex: item.columnPropName,
            width: (ListArray.length === index + 1) ? '' : (fullScreenMode ? 180 : 100),
            render: text => {
              if (text !== undefined && text !== null && text !== '' && item.dataType === 'bigdecimal')
                text = React.Component.prototype.filterMoney(text)
              return <span
                className={widget.fixedColumnsNum && widget.fixedColumnsNum > index ? `need-limit ${fullScreenMode ? 'full-screen-mode' : ''}` : ''}>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement={item.dataType === 'bigdecimal' ? 'topRight' : 'topLeft'}
                       content={text}>{text}</Popover> : '-'}
          </span>
            }
          });
        });
        return { columns: results, headerNum: 1 };
      } else {
        let results = [];
        let ListArray = deepCopy(widget.reportChartDetails);
        ListArray && ListArray.forEach((item, index) => {
          results.push({
            title: item.fieldDisplayName || '-',
            key: item.columnPropName,
            fixed: widget.fixedColumnsNum && widget.fixedColumnsNum > index ? 'left' : false,
            dataIndex: item.columnPropName,
            width: (ListArray.length === index + 1) ? '' : (fullScreenMode ? 180 : 100),
            render: text => {
              if (text !== undefined && text !== null && text !== '' && item.dataType === 'bigdecimal')
                text = React.Component.prototype.filterMoney(text)
              return <span
                className={widget.fixedColumnsNum && widget.fixedColumnsNum > index ? `need-limit ${fullScreenMode ? 'full-screen-mode' : ''}` : ''}>
            {(text !== undefined && text !== null && text !== '') ?
              <Popover zIndex={fullScreenMode ? 10030 : 1030} placement={item.dataType === 'bigdecimal' ? 'topRight' : 'topLeft'}
                       content={text}>{text}</Popover> : '-'}
          </span>
            }
          });
        });
        return { columns: results, headerNum: 1 };
      }
    }
  };

  getPromiseData = (params, pagination) => {
    let promiseData = this.promiseData(params, pagination);
    this.props.handleOverPromise && this.props.handleOverPromise(promiseData);
    return promiseData
  }

  promiseData = (params, pagination) => {
    const { data, widget, searchParamsData, isPreview, chartLinkableParams } = this.props;
    if (widget.key === 'perspective') {  //透视图    因为透视图  和 其他图标 数据结构 大相径庭 所以单独拿出来写逻辑
      if (data) {
        return new Promise((resolve, reject) => {
          resolve({ data: data });
        });
      } else {
        this.setState({ isOutOfService: false });
        return new Promise((resolve, reject) => {
          CustomReportService.getSingleChartData(
            widget.reportId,
            widget.id,
            0,
            100,
            isPreview,
            true,
            (searchParamsData && searchParamsData.concat(chartLinkableParams)) || []
          )
            .then((res) => {
              if (res.status === 200) {
                let ResData = res.data[0];
                if (res.data && res.data.length === 0) {
                  resolve({ data: [], noMoreData: true });
                  return
                }
                if (ResData.showFlag) {
                  let dimensionKeyMap = Object.keys(ResData.columnData.length && ResData.columnData[0]['dimensionColumns']);
                  let CopyData = deepCopy(ResData);
                  let ColData = deepCopy(ResData.columnData);
                  let metaData = deepCopy(ResData.metaData);

                  ResData.columnData.forEach((colData, colIndex) => {
                    colData.indicatorValues.forEach((value, valueIndex) => {
                      metaData[valueIndex][`${colData.indicatorName}-${colIndex}`] = value;
                      metaData[valueIndex][`uniqueKey`] = `${colIndex}-${valueIndex}`;
                      delete metaData[valueIndex][colData.indicatorName];
                    });
                  });
                  resolve({ data: metaData, noMoreData: true });

                  this.setState({ CopyData, ColData, metaData, dimensionKeyMap });
                } else {
                  this.setState({isOutOfService: true});
                  this.props.onOutOfService && this.props.onOutOfService();
                  reject(res);
                }
              }
            })
            .catch((err) => {
              reject(err);
            });
        });
      }
    } else { //明细表
      if (data) {
        return new Promise((resolve, reject) => {
          resolve({ data: data });
        });
      } else {
        return new Promise((resolve, reject) => {
          CustomReportService.getSingleChartData(
            widget.reportId,
            widget.id,
            pagination.page,
            pagination.size,
            isPreview,
            true,
            (searchParamsData && searchParamsData.concat(chartLinkableParams)) || []
          )
            .then((res) => {
              if (res.status === 200) {
                res.data.forEach((data, index)=>{
                  res.data[index].uniqueKey = pagination.page + 1 + pagination.size*pagination.page + index;
                })
                resolve(res);
              }
            })
            .catch((err) => {
              reject(err);
            });
        });
      }
    }
  };

  callbackDataList = (list) => {
    this.setState({ dataList: list });
  };

  render() {
    const { isOutOfService } = this.state;
    const {
      widget, selectShowDataList, fullScreenMode, selectDimensionRowDataList,
      selectDimensionDataList, selectIndicatorDataList
    } = this.props;
    let { columns, headerNum } = this.handleColumns(widget, selectShowDataList, selectDimensionRowDataList, selectDimensionDataList, selectIndicatorDataList);

    return (
      <div className='custom-report-table-my-style'>
        <ReportTable
          // title={'表格title'}
          cols={24}
          headerNum={headerNum}
          fullScreenMode={fullScreenMode}
          columns={columns}
          isOutOfService={isOutOfService}
          isColumsDefineByData={widget.key === 'perspective'}
          callbackDataList={this.callbackDataList}
          fetchMethod={this.getPromiseData}
          onRef={ref => this.onMountCharts = ref}
          dataLength={1}
          reportKey='customReportKey'
        />
        {isOutOfService &&
        <div className="empty-content">
          <img className='empty-content-image'
               onMouseDown={e=>e.preventDefault()}
               src={noDataImg}/>
          <p className="empty-content-desc">
            {messages('basic-10.key164')/*数据量太大超过服务上限，请重新调整设置*/}
          </p>
        </div>
        }
      </div>
    );
  }
}

IndexTable.propTypes = {};

export default IndexTable;
